package com.fz.song.springsecurydemo.config;

import com.fz.song.springsecurydemo.handler.MyFailureHandler;
import com.fz.song.springsecurydemo.handler.MySuccessHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                //自定义用户名参数
                .usernameParameter("username")
                //自定义密码参数
                .passwordParameter("password")
                //自定义登录页面
                .loginPage("/login.html")
                //自定义登录接口地址,必须和表单接口的一样
                .loginProcessingUrl("/login")
                //登录成功后跳转路径,必须是post请求
                //.successForwardUrl("/toMain")
                //自己指定登录成功后的处理器
                .successHandler(new MySuccessHandler("http://127.0.0.1:8080/main.html"))
                //登录失败跳转页面
                //.failureForwardUrl("/toError")
                //自定义登录失败后的处理器
                .failureHandler(new MyFailureHandler("http://127.0.0.1:8080/error.html"))


        ;
        http.authorizeRequests()
                //permitAll:放行所有
                .antMatchers("/login.html", "/error.html").permitAll()
                //anyRequest:所有请求,authenticated:需要授权
                .anyRequest().authenticated();

        http.csrf().disable();
    }
}
